<?php
// +--------------+--------------+------+-----+---------+----------------+
// | Field        | Type         | Null | Key | Default | Extra          |
// +--------------+--------------+------+-----+---------+----------------+
// | id           | int(11)      | NO   | PRI | NULL    | auto_increment |
// | title        | varchar(60)  | YES  |     |         |                |
// | type         | varchar(15)  | YES  |     |         |                |
// | pc_cover_id  | int(11)      | YES  |     | 0       |                |
// | wap_cover_id | int(11)      | YES  |     | 0       |                |
// | status       | tinyint(1)   | YES  |     | 0       |                |
// | user_id      | int(11)      | YES  |     | 0       |                |
// | create_time  | int(11)      | YES  |     | 0       |                |
// | update_time  | int(11)      | YES  |     | 0       |                |
// | link_url     | varchar(255) | YES  |     |         |                |
// | start_time   | int(11)      | YES  |     | 0       |                |
// | end_time     | int(11)      | YES  |     | 0       |                |
// +--------------+--------------+------+-----+---------+----------------+
namespace app\common\model;
use think\Loader;
use think\Config;
use think\Db;
class Banner extends Base{
  protected $auto = ['user_id'];

  /**
   * 添加或更新Banner Item
   * @Author zhanghong
   * @Date   2017-04-30
   * @param  array      $data Form提交的数据信息
   * @param  integer    $id   强制指定主键ID
   * @return array
   */
  public function createOrUpdate($data, $id = 0){
    $res = ["status" => false, "msg" => "Banner保存失败"];
    $validate = Loader::validate("Banner");
    if($validate->check($data)){
      if($id > 0){
        $data["id"] = $id;
      }
      if(empty($data["id"])){
        $this->save($data);
      }else{
        $this->isUpdate(true)->save($data);
      }
      $res = ["status" => true, "msg" => "Banner保存成功"];
    }else{
      $res["msg"] = $validate->getError();
    }
    return $res;
  }

 
  /**
   * 管理员查询方法
   * @Author zhanghong
   * @Date   2017-04-30
   * @param  array      $param     查询参数
   * @param  integer    $page_rows 每页显示行数
   * @return \think\paginator\Collection
   */
  public function managerSelect($param, $page_rows = 15){
    $prefix = Config::get("database.prefix");

    $this->searchWhere($param)
         ->join("{$prefix}user", "{$prefix}user.id={$prefix}banner.user_id", "LEFT")
         ->join("{$prefix}upload wap_upload", "{$prefix}banner.wap_cover_id=wap_upload.id", "LEFT");

    $options = $this->getOptions();
    $bind    = $this->getBind();
    $total_count = $this->count("DISTINCT {$prefix}banner.id");
    
    $select_fields = [];
    $banner_fields = ["id", "title", "update_time", "status","start_time","end_time"];
    foreach ($banner_fields as $idx => $key) {
      array_push($select_fields, "{$prefix}banner.{$key}");
    }
    array_push($select_fields, "{$prefix}user.nickname AS user_nickname");
    array_push($select_fields, "{$prefix}user.avatar AS user_avatar");
    array_push($select_fields, "wap_upload.save_path AS wap_cover_path");
    
    $this->options($options)->bind($bind)->field($select_fields)
         ->group("{$prefix}banner.id")->order("{$prefix}banner.id DESC");

    $config["query"] = ["query" => $param];
    // 分页参数名是 page ，paginate方法内有获取到该值的方法
    $page = 1;
    if(isset($param["page"])){
      $page = intval($param["page"]);
    }
    $config["page"] = $page;
    $paginate = $this->paginate($page_rows, $total_count, $config);
    return $paginate;
  }

  /**
   * 最新列表
   * @Author zhanghong
   * @Date   2017-05-04
   * @param  [type]     $param       [description]
   * @param  integer    $limit_count [description]
   * @return [type]                  [description]
   */
  public function activeTopSelect($type, $limit_count = 5){
    $prefix = Config::get("database.prefix");
    $current_time = time();
    $select_fields = [];
    $banner_fields = ["id", "title", "link_url"];
    foreach ($banner_fields as $idx => $key) {
      array_push($select_fields, "{$prefix}banner.{$key}");
    }
    array_push($select_fields, "wap_upload.save_path AS wap_cover_path");
    
    $param = ["type" => $type, "only_active" => 1,"start_time" => $current_time, "end_time" =>$current_time]; 
    $banners = $this->searchWhere($param)->field($select_fields)
                    ->join("{$prefix}upload wap_upload", "{$prefix}banner.wap_cover_id=wap_upload.id", "LEFT")
                    ->order("{$prefix}banner.id DESC")
                    ->select();

    $OptionsModel = new Options();
    $site_root = $OptionsModel->getSiteHost();
    
    foreach ($banners as $key => &$item) {
      $target = "_self";
      $link_url = $item["link_url"];
      if(empty($link_url)){
        $link_url = "javascript:void(0)";
      }else{
        // 站内、站外链接全在新页面打开
        $target = "_blank";
      }
      $item["link_url"] = $link_url;
      $item["target"] = $target;

    }

    return $banners;
  }

  /**
   * 随机查询某类型一条记录
   * @Author zhanghong
   * @Date   2017-05-01
   * @param  string     $type Bannder类型
   * @return array
   */
  public function randFindByType($type){
    $prefix = Config::get("database.prefix");
    $select_fields = [
      "{$prefix}banner.id",
      "wap_upload.save_path AS wap_cover_path",
    ];
    $current_time = time();
    $item = $this->field($select_fields)
                 ->join("{$prefix}upload wap_upload", "{$prefix}banner.wap_cover_id=wap_upload.id")
                 ->where("{$prefix}banner.type", $type)
                 ->where("{$prefix}banner.status", 1)
                 ->where("{$prefix}banner.start_time < $current_time")
                 ->where("({$prefix}banner.end_time > $current_time || {$prefix}banner.end_time = 0)")
                 ->order("RAND()")->find();
    return $item;
  }

  /**
   * 生成搜索条件
   * @Author zhanghong
   * @Date   2017-04-30
   * @param    array      $param 请求参数
   * @return   array             Select Map
   */
  private function searchWhere($param){
    $prefix = Config::get("database.prefix");
    if(!isset($param["type"]) || empty($param["type"])){
      $param["type"] = "empty";
    }
    
    foreach ($param as $key => $value) {
      if(empty($value)){
        continue;
      }
      switch ($key) {
      case "type":
        $this->where("{$prefix}banner.type", $value);
        break;
      case "only_active":
        $this->where("{$prefix}banner.status", 1);
        break;
      case "start_time": 
        $this->where("{$prefix}banner.start_time < $value");
        break;
      case "end_time":
        $this->where("{$prefix}banner.end_time > $value || {$prefix}banner.end_time = 0");
        break;
      case "keyword":
        if(empty($value)){
          continue;
        }else{
          $keyword = "%{$value}%";
        }
        $this->where("{$prefix}banner.title", "like", $keyword);
        break;
      case "user_name":
        if(empty($value)){
          continue;
        }else{
          $keyword = "%{$value}%";
        }
        $this->where("{$prefix}user.name|{$prefix}user.nickname|{$prefix}user.mobile", "like", $keyword);
        break;
      }
    }
    
    return $this;
  }
}